<template>
  <div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addMenu({id:0})">
          新增菜单
        </el-button>
      </div>
      <el-table :data="tableData" row-key="id">
        <el-table-column align="left" label="菜单名称" min-width="120" prop="authorityName">
          <template #default="scope">
            <span>{{ scope.row.meta.title }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="菜单类型" min-width="120" prop="type">
          <template #default="scope">
             <span v-if="scope.row.type==1">模块</span>
             <span v-if="scope.row.type==2">目录</span>
             <span v-if="scope.row.type==3">菜单</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="所属系统" min-width="100" prop="hidden">
          <template #default="scope">
            <span>{{ scope.row.system == 1 ? '客户端' : '管理端' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="路由地址" prop="path" />
        <el-table-column align="left" label="是否隐藏" min-width="100" prop="hidden">
          <template #default="scope">
            <span>{{ scope.row.hidden ? '隐藏' : '显示' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="是否外链" min-width="100" prop="hidden">
          <template #default="scope">
            <span>{{ scope.row.link == 1 ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="排序" min-width="70" prop="sort" />
        <el-table-column align="left" fixed="right" label="操作" min-width="160">
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="plus"
              @click="addMenu(scope.row)"
            >
              添加子菜单
            </el-button>
            <el-button type="primary" link icon="edit" @click="editMenu(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link icon="delete" @click="deleteMenu(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-drawer v-model="dialogFormVisible" :size="appStore.drawerSize" :before-close="handleClose" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ dialogTitle }}</span>
          <div>
            <el-button @click="closeDialog"> 取 消 </el-button>
            <el-button type="primary" @click="enterDialog"> 确 定 </el-button>
          </div>
        </div>
      </template>

      <warning-bar title="新增菜单，需要在角色管理内配置权限才可使用" />
      <el-form v-if="dialogFormVisible" ref="menuForm" label-width="90" :model="form" :rules="rules">
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="所属系统" prop="meta.title">
              <el-radio-group v-model="form.system">
                <el-radio :value="1" size="large">客户端</el-radio>
                <el-radio :value="2" size="large">管理端</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单类型" prop="meta.title">
              <el-radio-group v-model="form.type" :disabled="isAddSubMenu">
                <el-radio :value="1" size="large">模块</el-radio>
                <el-radio :value="2" size="large">目录</el-radio>
                <el-radio :value="3" size="large">菜单</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="meta">
              <el-input v-model="form.meta" placeholder="请输入"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级菜单">
              <el-cascader style="width: 100%;" :disabled="form.type == 1||isAddSubMenu" :options="tableData" :props="props1"
                clearable v-model="pids" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input v-model.number="form.sort" placeholder="请输入"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路由地址" prop="path">
              <el-input v-model="form.path" placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="是否外链">
              <el-radio-group v-model="form.link" class="ml-4">
                <el-radio :label="1" size="large">是</el-radio>
                <el-radio :label="2" size="large">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示状态">
              <el-radio-group v-model="form.hidden" class="ml-4">
                <el-radio :value="1" size="large">显示</el-radio>
                <el-radio :value="2" size="large">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="组件地址">
              <el-input v-model="form.component" placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import {
  updateBaseMenu,
  getMenuList,
  addBaseMenu,
  deleteBaseMenu,
  getBaseMenuById
} from '@/api/menu'
import WarningBar from '@/components/warningBar/warningBar.vue'
import { reactive, ref,onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { sortBySort } from '@/utils/format'
import { toLowerCase } from '@/utils/stringFun'
import pathInfo from '@/pathInfo.json'
import { useAppStore } from "@/pinia";

defineOptions({
  name: 'Menus'
})
const props1 = {
  checkStrictly: true,
  label: 'title',
  value: 'id'
}
const appStore = useAppStore()
const rules = reactive({
  meta: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入路由地址', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
})

const tableData = ref([])
// 查询
const getTableData = async () => {
  const res = await getMenuList()
  if (res.code == 200) {
    tableData.value = res.result
    tableData.value.forEach(m => {
      m.title = m.meta.title
      if (m.children.length > 0) {
        m.children.forEach(n => {
          n.title = n.meta.title
          if (n.children.length > 0) {
            n.children.forEach(k => {
              k.title = k.meta.title
            })
          }
        })
      }
    })
    tableData.value = sortBySort(tableData.value)
  }
}
onMounted(() => {
 
})

getTableData()

// 新增参数
const addParameter = (form) => {
  if (!form.parameters) {
    form.parameters = []
  }
  form.parameters.push({
    type: 'query',
    key: '',
    value: ''
  })
}

const fmtComponent = (component) => {
  form.value.component = component.replace(/\\/g, '/')
  form.value.name = toLowerCase(pathInfo['/src/' + component])
  form.value.path = form.value.name
}

// 删除参数
const deleteParameter = (parameters, index) => {
  parameters.splice(index, 1)
}

// 新增可控按钮
const addBtn = (form) => {
  if (!form.menuBtn) {
    form.menuBtn = []
  }
  form.menuBtn.push({
    name: '',
    desc: ''
  })
}

const form = ref({
  link: 2,
  system: 1,
  type: 1,
  path: '',
  name: '',
  hidden: 1,
  parentId: 0,
  component: '',
  meta: ''
})

const changeName = () => {
  form.value.path = form.value.name
}

const handleClose = (done) => {
  initForm()
  done()
}
// 删除菜单
const deleteMenu = (row) => {
  ElMessageBox.confirm(
    '此操作将永久删除所有角色下该菜单, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await deleteBaseMenu(row.id)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}
// 初始化弹窗内表格方法
const menuForm = ref(null)
const checkFlag = ref(false)
const initForm = () => {
  checkFlag.value = false
  menuForm.value.resetFields()
  form.value = {
    link: 2,
    system: 1,
    type: 1,
    path: '',
    name: '',
    hidden: 1,
    parentId: 0,
    component: '',
    meta: ''
  }
  pids.value = []
  isAddSubMenu.value = false
}
// 关闭弹窗

const dialogFormVisible = ref(false)
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}

const pids = ref([])
// 添加menu
const enterDialog = async () => {
  menuForm.value.validate(async (valid) => {
    if (valid) {
      form.value.name = form.value.path
      form.value.hidden = form.value.hidden == 1 ? false : true
      form.value.parentId = form.value.type == 1 ? 0 : pids.value[pids.value.length - 1]
      let res
      if (isEdit.value) {
        res = await updateBaseMenu(form.value)
      } else {
        res = await addBaseMenu(form.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}

const menuOption = ref([
  {
    ID: '0',
    title: '根菜单'
  }
])
const setOptions = () => {
  menuOption.value = [
    {
      ID: 0,
      title: '根目录'
    }
  ]
  setMenuOptions(tableData.value, menuOption.value, false)
}
const setMenuOptions = (menuData, optionsData, disabled) => {
  menuData &&
    menuData.forEach((item) => {
      if (item.children && item.children.length) {
        const option = {
          title: item.meta.title,
          ID: item.ID,
          disabled: disabled || item.ID === form.value.ID,
          children: []
        }
        setMenuOptions(
          item.children,
          option.children,
          disabled || item.ID === form.value.ID
        )
        optionsData.push(option)
      } else {
        const option = {
          title: item.meta.title,
          ID: item.ID,
          disabled: disabled || item.ID === form.value.ID
        }
        optionsData.push(option)
      }
    })
}

// 添加菜单方法，id为 0则为添加根菜单
const isEdit = ref(false)
const dialogTitle = ref('新增菜单')
const isAddSubMenu = ref(false)
const addMenu = (row) => {
  dialogTitle.value = '新增菜单'
  form.value.parentId = row.id
  if(row.type){
    form.value.type=row.type+1
    pids.value = getPid(row)
    isAddSubMenu.value = true
  }else{
    isAddSubMenu.value = false
  }
  isEdit.value = false
  //setOptions()
  dialogFormVisible.value = true
}
// 修改菜单方法
const editMenu = async (row) => {
  dialogTitle.value = '编辑菜单'
  //const res = await getBaseMenuById({ id })
  pids.value = getPids(row)
  
  form.value = JSON.parse(JSON.stringify(row))
  form.value.hidden = row.hidden ? 2 : 1
  form.value.meta = row.meta.title
  form.value.menuId = row.id
  console.log(row,form.value,'bnbn')
  isEdit.value = true
  //setOptions()
  dialogFormVisible.value = true
}

const getPids = (row) => {
  let res = []
  if (row.type == 1) {
    return []
  } else if (row.type == 2) {
    tableData.value.forEach(item => {
      if (item.children.length > 0) {
        item.children.forEach(m => {
          if (m.id == row.id) {
            res.push(item.id)
          }
        })
      }
    })
  } else {
    tableData.value.forEach(item => {
      if (item.children.length > 0) {
        item.children.forEach(m => {
          if (m.children.length > 0) {
            m.children.forEach(n => {
              if (n.id == row.id) {
                res.push(item.id)
                res.push(m.id)
              }
            })
          }
        })
      }
    })
  }
  return res
}

const getPid = (row)=>{
  let res = []
   if(row.type==1){
      res.push(row.id)
   }else{
    tableData.value.forEach(item => {
      if (item.children.length > 0) {
        item.children.forEach(m => {
          if (m.id == row.id) {
            res.push(item.id)
            res.push(row.id)
          }
        })
      }
    })
   }
   return res
}
</script>

<style scoped lang="scss">
.warning {
  color: #dc143c;
}

.icon-column {
  display: flex;
  align-items: center;

  .el-icon {
    margin-right: 8px;
  }
}

.flex {
  display: flex;
}
</style>
